"""
---------------------------------------------------------------------
- File: app_response.py
- Date: 2025/7/12
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 共享响应返回
---------------------------------------------------------------------
"""

from typing import Any
from typing import TypeVar, Generic

from fastapi.responses import ORJSONResponse
from pydantic import BaseModel

# 使用TypeVar 来支持泛型
T = TypeVar("T")


class UnifiedResponse(BaseModel, Generic[T]):
    """
    统一响应体模型
    """

    """代码"""
    code: int = 200
    """信息"""
    msg: str = "OK"
    """数据"""
    data: T | None = None


def success(
    data: Any = None, code: int | str = 200, msg: str = "success"
) -> ORJSONResponse:
    """
    成功响应
    """
    return ORJSONResponse(
        status_code=200,  # HTTP 状态码固定200， 正常的响应
        headers={"Access-Control-Allow-Origin": "*"},  # 允许跨域访问
        content=UnifiedResponse(data=data, code=code, msg=msg).model_dump(),
    )


def fail(
    data: Any = None,
    code: int | str = 201,
    msg: str = "fail",
    status_code: int | str = 201,
) -> ORJSONResponse:
    """
    失败响应
    """
    return ORJSONResponse(
        status_code=status_code,  # HTTP 状态码固定201
        headers={"Access-Control-Allow-Origin": "*"},  # 允许跨域访问
        content=UnifiedResponse(data=data, code=code, msg=msg).model_dump(),
    )
